<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2016/7/7
 * Time: 22:08
 */
use app\assets\AppAsset;
use yii\widgets\ActiveForm;
use yii\helpers\Html;

AppAsset::register($this);

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this, $base . "/css/shop-bag.css");
AppAsset::addCss($this, $base . "/css/ToPay.css");
$this->title = '购物车';
$ddd = [20, 20, 20, 20];
?>
<div style="padding-left: 10px;padding-right: 10px" id="shop_bag" data-role="page">

    <section class="gwc_section">
        <div class="product_title">
            <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td width="24px"><img class="shop_icon" src="<?= $base ?>/images/home_icon.png"/>
                    </td>
                    <td><span><?=$shopName?></span></td>
                    <td align="right"><span id="edit_parent" onclick="myDelete()">编辑</span>
                    </td>
                </tr>
            </table>
        </div>
        <?php for ($j = 0; $j < count($commodities); $j++) { ?>
            <div class="product_hover">
                <table width="100%" cellpadding="0" cellspacing="0">
                    <tr>
                        <td style="vertical-align: middle;width: 10%;"><input indextag="<?= $j ?>" name="<?= $j ?>" type="checkbox"
                                                                  id="editbox" class="editbtn_<?= $j ?>"/></td>

                        <td style="width: 18%!important;"><div class="image-div"><img class="product_icon"
                                                   src="<?= $commodities[$j]['pic_url'] ?>"/></div></td>
                        <td style="padding-left: 1%;line-height: 100%;width: 25%;">
                            <p style="height: 30px;overflow: hidden;"><?= $commodities[$j]['commodity_name'] ?></p>

                            <p><?php for ($i = 0; $i < count($attrsAll[$j]); $i++) { ?>
                                    <?= $attrsAll[$j][$i]['attr_opt_name'] ?>
                                <?php } ?>
                            </p>

                            <p style="color: #FFA500;">￥<?= $commodities[$j]['price'] ?></p>
                        </td>
                        <td   id="buybox_<?=$j?>" style="position: absolute;left: 90%;margin-top: 64px;font-size: 12px;">x<span  id="buyNum_<?=$j?>"><?=$carts[$j]['shop_num']?></span> </td>

                         <td style="width: 35%!important;padding-left: 1%;display: none" id="numbtn<?=$j?>">
<!--                             --><?//=$carts[$j]['shop_num']?>

                        <div class="buymenu<?=$j?>" style="font-size: 14px;color: #4A4A4A;position: relative;top: 1px;left: 7px;">购买数量:
                            <br/>
                            (库存: <span class ='stock_num'>
                     <?=$commodities[$j]['stock_num']?>


                    </span>)
                        </div>
                        <div style="clear: both"></div>
                        <div class="cpsx_info_num" style="position: relative;left: 7px;">
                            <div class="deleteDiv" onclick="deletesSum(<?=$j?>)">-</div>
                            <div id="sumId_<?=$j?>" class="shopSum" ><?=$carts[$j]['shop_num']?></div>
                            <div class="addDiv" onclick="addSum(<?=$j?>)">+</div>
                        </div>
                        </td>



                        <td id="goods_<?= $j ?>" style="display: none;background:#FF0033;width: 20%; "
                            align="right" onclick="deleteCart(<?= $carts[$j]['cart_id']?>)">
                            <p style="text-align:center;color: #ffffff">删除</p>
                        </td>
                    </tr>
                </table>
            </div>
        <?php } ?>
        <?php for ($j = 0; $j < count($commodities_out_date); $j++) { ?>
            <div class="product_hover">
                <table width="100%" cellpadding="0" cellspacing="0">
                    <tr>
                        <td style="vertical-align: middle;width: 30px"><div style="font-size: 15px;background-color: #e2e2e2">失效</div></td>
                        <td width="90px"><div class="image-div"><img class="product_icon"
                                                                     src="<?= $commodities_out_date[$j]['pic_url'] ?>"/></div></td>
                        <td style="padding-left: 10px;line-height: 100%">
                            <p style="height: 30px;overflow: hidden;"><?= $commodities_out_date[$j]['commodity_name'] ?></p>
                            <p style="color: #FFA500;">￥<?= $commodities_out_date[$j]['price'] ?></p>
                        </td>
                        <td id="goods_<?= count($commodities)+$j ?>" style="display: none;background:#FF0033;width:50px "
                            align="right" onclick="deleteCart(<?= $carts[$j]['cart_id']?>)">
                            <p style="text-align:center;color: #ffffff">删除</p>
                        </td>
                    </tr>
                </table>
            </div>
        <?php } ?>

        <?php if(count($commodities)==0&&count($commodities_out_date)==0){?>
           <div id="cartContainer">
               <div class="emptyList" style="padding-top: 40px">
                   <div class="emptyListHeader">
                       <h4>购物车快饿瘪了 T.T</h4>
                       <span>快给我挑点宝贝</span>
                   </div>
                   <div class="emptyListContent">
                       <a href="home" class="goHome">去逛逛</a>
                   </div>

               </div>
           </div>


        <?php } ?>



    </section>

    <div style="height: 45px"></div>
    <footer class="gwc_footer">
        <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td><input type="checkbox" id="allselect"/> 全选</td>
                <td align="right" style="padding-right: 10px">
                    <p>合计：<span id="sum_price" class="txtred">0.00</span></p>
                    <input id="sumInput" name="money" style="display: none;" value="0.00">

                    <p class="txtfont12">不含运费</p>
                </td>
                <td align="right" width="90" style="padding-right: 10px"><div class="pay_button" onclick="checkForm()">结算</div></td>
            </tr>
        </table>
    </footer>

</div>

<script>

    $(document).ready(function(){
        function imageLoaded(){
            $(this).attr("hidden",false);
            var height = $(this).css('height');

            var width = $(this).css('width');
            if (parseInt(height.substring(0,height.length-2))>parseInt(width.substring(0,width.length-2))){
                $(this).css('height',"100%");
                $(this).width('auto');
            }else {
                $(this).css('width',"100%")
                $(this).height('auto');
            }
        }
        $(".product_icon").each(function(){
            if(this.complete){
                imageLoaded.call(this);
            }else{
                $(this).one('load', imageLoaded);
            }
        });
    });

    $(document).ready(function () {
        var money = parseFloat(0.00).toFixed(2);
        var commodity = (<?php echo json_encode($commodities)?>);
        var attr = (<?php echo json_encode($attrsAll)?>);

        for (var i = 0; i < commodity.length; i++) {
            var isChoose = document.getElementsByName(i.toString())[0].checked;
            if (isChoose) {
                var sum =parseInt(document.getElementById("sumId_"+i).innerText);
                var index = document.getElementsByName(i.toString())[0].getAttribute('indextag');
                money = (parseFloat(commodity[i].price)*sum + parseFloat(money)).toFixed(2);
            }
        }
        document.getElementById("sum_price").innerText = money.toString();
        document.getElementById("sumInput").value = money.toString();

        function checkIsSelect() {
            var alleditlength = $("input:checkbox[id=editbox]").length;
            var allcheckedlength = $("input:checkbox[id=editbox]:checked").length;
            if (alleditlength == allcheckedlength) {
                $("#allselect").prop("checked", true);
            } else {
                $("#allselect").prop("checked", false);
            }
        }

        $(document).on('click', "#editbox", function () {

            var parentlength = $(this).parents(".gwc_section").children().length - 1;
            var childlength = $(this).parents(".gwc_section").children(".product_hover").find(":checked").length;
            if (parentlength == childlength) {
                $(this).parents(".gwc_section").children(".product_title").find("input:checkbox").prop("checked", true);
            } else {
                $(this).parents(".gwc_section").children(".product_title").find("input[type=checkbox]").prop("checked", false);
            }

            var index = $(this).attr("indextag");

            var firstSum = document.getElementById("sum_price").innerText;
            var sum =parseInt(document.getElementById("sumId_"+index).innerText);
            if (this.checked) {

                money = (parseFloat(firstSum) + parseFloat(commodity[index].price)*parseFloat(sum)).toFixed(2);

            } else {
                money = (parseFloat(firstSum) - parseFloat(commodity[index].price)*parseFloat(sum)).toFixed(2);

            }
            document.getElementById("sum_price").innerText = money.toString();
            document.getElementById("sumInput").value = money.toString();
            checkIsSelect();

        });

        $("#allselect").click(function () {
            $(":checkbox").prop("checked", this.checked);

            money = parseFloat(0.00).toFixed(2);
            if (this.checked) {
                for (var i = 0; i < commodity.length; i++) {
                    var sum =parseInt(document.getElementById("sumId_"+i).innerText);
                    money = (parseFloat(commodity[i].price)*sum + parseFloat(money)).toFixed(2);
                }
            }

            document.getElementById("sum_price").innerText = money.toString();
            document.getElementById("sumInput").value = money.toString();
        });


    });

    var cart = (<?php echo json_encode($carts)?>);
    var commodity = (<?php echo json_encode($commodities)?>);
    var attr = (<?php echo json_encode($attrsAll)?>);

    function myDelete() {
        for (var i = 0; i < cart.length; i++) {
            if (document.getElementById("goods_" + i).style.display == "none") {
                document.getElementById("edit_parent").text = "完成";
                document.getElementById("goods_" + i).style.display = "";
                document.getElementById("numbtn"+i).style.display="";
                document.getElementById("buybox_"+i).style.display="none";
            } else {
                document.getElementById("edit_parent").text = "编辑";
                document.getElementById("goods_" + i).style.display = "none";
                document.getElementById("numbtn"+i).style.display="none";
                document.getElementById("buybox_"+i).style.display="";

            }
        }
    }

    function checkForm() {

        var num = $("input:checkbox[id=editbox]:checked").length;
        if (num < 1) {
            alert("请先选择商品");
            return false;
        }

        var cartIds = new Array();
        var commodityIds = new Array();
        var attrIds = new Array();
        var sums = new Array();

        for (var i = 0; i < commodity.length; i++) {
            var isChoose = document.getElementsByName(i.toString())[0].checked;
            if (isChoose) {
                cartIds.push(cart[i].cart_id);
                commodityIds.push(commodity[i].commodity_id);
                attrIds.push(getCommodityMsg(i));
                var sum =parseInt(document.getElementById("sumId_"+i).innerText);
                sums.push(sum);
                console.log('gggg',sums);


            }
        }
        location.href = "to-pay?commodity_ids=" +JSON.stringify(commodityIds) +"&attr_opt_ids=" +JSON.stringify(attrIds)
        +"&cart_ids="+JSON.stringify(cartIds)+"&sums="+JSON.stringify(sums);
    }

    function getCommodityMsg(position){
        var attr_opts = attr[position];
        var attr_opt_ids = new Array();
        for (var i=0;i<attr_opts.length;i++){
            attr_opt_ids.push(attr_opts[i].attr_opt_id);   //获取商品规格的attr_opt_id
        }
        return attr_opt_ids;
    }

    function deleteCart(cart_id){
        $.ajax({
//            type:"POST",
//            dataType:"json",
            data:{"cart_id":cart_id},
            url:"delete-cart",
            success:function(json){
//                console.log("123",json);
                alert("删除成功");
                location.reload();
            },
            error:function(data){
//                console.log(data);
                alert("删除失败");
            }
        });
    }



    function deletesSum(position){
        var $sum = document.getElementById("sumId_"+position).innerText;


        if(parseInt($sum) > 1){
            $sum = (parseInt($sum) - 1).toString();
            document.getElementById("sumId_"+position).innerText = $sum;
            document.getElementById("buyNum_"+position).innerText=$sum;
//            totalSum();
        }else{
            alert("最少数量为1")
        }
        totalSum();
    }


    function addSum(position){
        var $sum = document.getElementById("sumId_"+position).innerText;
        $sum = (parseInt($sum) + 1).toString();

        document.getElementById("sumId_"+position).innerText = $sum;
        document.getElementById("buyNum_"+position).innerText=$sum;
        if(parseInt($sum)> parseInt($('.buymenu'+position).find('span.stock_num').text())){
            alert('非常抱歉,因库存不足,无法添加更多商品');
            document.getElementById("sumId_"+position).innerText = ($sum-1).toString();
        }
         totalSum();
    }

    function totalSum(){
        var total = parseFloat(0.00).toFixed(2);
        var commodity = (<?php echo json_encode($commodities)?>);
        console.log('hah',commodity);
        for(var j= 0 ; j < commodity.length ;j++){
           // var checkboxBtn=$(this).parents(".gwc_section").children(".product_hover").find("input:checkbox").is(":checked");
//              var isChecked=$("input[name=j]").is(":checked");
//            console.log('isisi',!isChecked);
            var isChecked=$(".editbtn_"+j).is(':checked');
            console.log('sss',isChecked);
            if(isChecked){
                var $sum = document.getElementById("sumId_" + j).innerText;
                if(!$sum){
                    $sum = 1;
                }

                total = parseFloat($sum) * parseFloat(commodity[j].price) + parseFloat(total);


            }

        }

        document.getElementById("sum_price").innerText  = parseFloat(total).toFixed(2).toString();
       // document.getElementById("sum_price").innerText = money.toString();

    }

</script>